package com.zhangjun.chat.socket.handler;

import com.alibaba.fastjson.JSON;
import com.zhangjun.chat.application.UserService;
import com.zhangjun.chat.domain.user.model.GroupsInfo;
import com.zhangjun.chat.domain.user.model.TalkBoxInfo;
import com.zhangjun.chat.domain.user.model.UserFriendInfo;
import com.zhangjun.chat.domain.user.model.UserInfo;
import com.zhangjun.chat.infrastructure.common.SocketChannelUtil;
import com.zhangjun.chat.protocol.login.LoginRequest;
import com.zhangjun.chat.protocol.login.LoginResponse;
import com.zhangjun.chat.protocol.login.dto.UserFriendDto;
import com.zhangjun.chat.socket.MyBizHandler;
import io.netty.channel.Channel;


import java.util.ArrayList;
import java.util.List;

/**
 * 博  客：http://bugstack.cn
 * 公众号：bugstack虫洞栈 | 沉淀、分享、成长，让自己和他人都能有所收获！
 * create by 小傅哥 on @2020
 * <p>
 * 登陆请求处理
 */
public class LoginHandler extends MyBizHandler<LoginRequest> {

    public LoginHandler(UserService userService) {
        super(userService);
    }


    @Override
    public void channelRead(Channel channel, LoginRequest msg) {

        logger.info("登陆请求处理：{} ", JSON.toJSONString(msg));

        // 1. 登陆失败返回false

        boolean auth = userService.checkAuth(msg.getUserId(), msg.getUserPassword());

        if (!auth) {

            // 传输消息

            channel.writeAndFlush(new LoginResponse(false));

            return;

        }

        // 2 登陆成功绑定用户ID

        SocketChannelUtil.addChannel(msg.getUserId(), channel);

        // 3. 初始化数据，反馈消息；用户信息、用户对话框列表、好友列表、群组列表

        // 3.1 用户信息
        LoginResponse loginResponse = new LoginResponse();

        UserInfo userInfo = userService.queryUserInfo(msg.getUserId());

        // 3.2 对话框

        List<TalkBoxInfo> talkBoxInfoList = new ArrayList<>();

        // 3.3 群组

        List<GroupsInfo> groupsInfoList = new ArrayList<>();

        // 3.4 好友

        List<UserFriendInfo> userFriendInfoList = userService.queryUserFriendInfoList(msg.getUserId());
        for (UserFriendInfo userFriendInfo : userFriendInfoList) {
            UserFriendDto userFriend = new UserFriendDto();
            userFriend.setFriendId(userFriendInfo.getFriendId());
            userFriend.setFriendName(userFriendInfo.getFriendName());
            userFriend.setFriendHead(userFriendInfo.getFriendHead());
            loginResponse.getUserFriendList().add(userFriend);
        }


        // 组装消息包


        loginResponse.setSuccess(true);

        loginResponse.setUserId(userInfo.getUserId());

        loginResponse.setUserNickName(userInfo.getUserNickName());

        loginResponse.setUserHead(userInfo.getUserHead());

        // 传输消息

        channel.writeAndFlush(loginResponse);

    }
}
